package com.xb.loan.cashier.alipay.web;

import com.opensymphony.xwork2.ActionSupport;
import com.xb.loan.cashier.alipay.util.*;
import com.xb.loan.cashier.alipay.util.*;
import com.xb.loan.cashier.alipay.web.bean.EnCashValueBean;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Scope("prototype")
public class EncashAction extends ActionSupport {

    @Value("${sign_type}")
    private String sign_type;

    @Value("${md5key}")
    private String md5key;

    private File bptb_pay_file;

    private String bptb_pay_fileFileName;

    private String file_name;

    public String getFile_name() {
        return file_name;
    }

    public void setFile_name(String file_name) {
        this.file_name = file_name;
    }

    public String getBptb_pay_fileFileName() {
        return bptb_pay_fileFileName;
    }

    public void setBptb_pay_fileFileName(String bptb_pay_fileFileName) {
        this.bptb_pay_fileFileName = bptb_pay_fileFileName;
    }

    public File getBptb_pay_file() {
        return bptb_pay_file;
    }

    public void setBptb_pay_file(File bptb_pay_file) {
        this.bptb_pay_file = bptb_pay_file;
    }

    public void doExecute() throws Exception {
        PrintWriter out = null;
        try {
            final Map<String, String> params = WebUtil.getRequetParams(ServletActionContext.getRequest());
            if ("bptb_result_file".equals(params.get("service"))) {
                downLoad();
                return;
            }
            if ("bptb_refund_file".equals(params.get("service"))) { //退票
                downLoadRefund(params);
                return;
            }
            processUpLoadFile();
            String contentType = "text/html;charset=utf-8";
            ServletActionContext.getResponse().setContentType(contentType);
            out = ServletActionContext.getResponse().getWriter();
            out.print("文件上传成功!");
            out.flush();

            new Thread() {
                public void run() {
                    try {
                        Thread.sleep(2000);
                        AlipaySubmit.buildAsyncResponse(buildAsycRetMap(params), params.get("notify_url"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                };
            }.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }

    }
    public void downLoadRefund(Map<String, String> params) throws Exception {  //下载退票文件
    	System.out.println("downLoadRefund params="+params.toString());
    	HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("application/octet-stream;charset=GBK");
        response.setHeader("Content-Disposition", "attachment;");
        String realpath = ServletActionContext.getServletContext().getRealPath("/refundFiles");
        String date = params.get("date").toString();
        String desFile = realpath + File.separator + "RESULT_"+date+"_R.zip";
        System.out.println("downloadFile =" +desFile);
        InputStream in = null;
        OutputStream out = null;
        try {
        	File file = new File(desFile);
        	if(!file.exists()){
        		System.out.println("文件不存在！　filePath="+file.getAbsolutePath());
        		return;
        	}
            in = new FileInputStream(desFile);
            int len = 0;
            byte[] buffer = new byte[1024];
            response.setCharacterEncoding("GBK");
            out = response.getOutputStream();
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            if(out != null){
            	try {
            		out.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    public void downLoad() throws Exception {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("application/octet-stream;charset=GBK");
        response.setHeader("Content-Disposition", "attachment;  filename=" + new String(file_name.getBytes("GBK"), "ISO8859-1"));
        String realpath = ServletActionContext.getServletContext().getRealPath("/file");
        String desFile = realpath + File.separator + "RESULT_" + trimFileType(file_name) + ".zip";
        System.out.println("downloadFile =" +desFile);
        InputStream in = null;
        OutputStream out = null;
        try {
        	File file = new File(desFile);
        	if(!file.exists()){
        		return;
        	}
            in = new FileInputStream(desFile);
            int len = 0;
            byte[] buffer = new byte[1024];
            response.setCharacterEncoding("GBK");
            out = response.getOutputStream();
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            if(out != null){
            	try {
            		out.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }

    public void processUpLoadFile() throws IOException {
        String realpath = ServletActionContext.getServletContext().getRealPath("/file");
        System.out.println("realpath: " + realpath);
        System.out.println("bptb_pay_fileFileName:= " + bptb_pay_fileFileName);
        if (bptb_pay_file != null) {
            File savefile = new File(new File(realpath), bptb_pay_fileFileName);
            if (!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();
            FileUtils.copyFile(bptb_pay_file, savefile);
            List<List<String>> data = CSVUtils.readCSVFile(savefile.getAbsolutePath());
            String collectFilePath = realpath + File.separator + "ALIPAY__RESULT.csv";
            String detailFilePath = realpath + File.separator + bptb_pay_fileFileName;
            String refundsFilePath = realpath + File.separator + "R__RESULT.csv";
            String refundsPath = realpath + File.separator + "R__RESULT";
            Map<String,Double> map = new HashMap<String,Double>();
            List<List<String>> listDetail = EnCashValueBean.getAlipayEncashDetail(data,map);
            List<List<String>> listCollect = EnCashValueBean.getAlipayEncashCollect(bptb_pay_fileFileName, data,map);
            CSVUtils.createCSVFile(collectFilePath, listCollect);
            CSVUtils.createCSVFile(detailFilePath, listDetail);
            String desFile = realpath + File.separator + "RESULT_" + trimFileType(bptb_pay_fileFileName) + ".zip";
            ZipUtil.zipCompress(new String[] { collectFilePath, detailFilePath }, desFile);
            
            List<List<String>> listRefund = EnCashValueBean.getRefundList(listDetail);
            CSVUtils.createCSVFile(refundsFilePath, listRefund);
            CSVUtils.createCSVFile(refundsPath, listRefund);
            ZipUtil.zipCompress(new String[] { refundsFilePath, refundsPath }, realpath + File.separator + "RESULT_R.zip");
        }

    }

    private Map<String, String> buildAsycRetMap(Map<String, String> params) {
        Map<String, String> retMap = new HashMap<String, String>();
        retMap.put("notify_type", "bptb_result_notify");
        retMap.put("notify_time", UtilDate.getDateFormatter());
        // retMap.put("notify_id", UtilDate.getOrderNum());
        retMap.put("pay_date", UtilDate.getDate());
        retMap.put("flag", "bptb_result_file");
        retMap.put("file_name", bptb_pay_fileFileName);
        retMap.put("sign_type", sign_type);
        Map<String, String> sParaNew = AlipayCore.paraFilter(retMap);
        String preSignStr = AlipayCore.createLinkString(sParaNew);
        System.out.println(preSignStr);
        ;
        String sign = MD5.sign(preSignStr, md5key, "utf-8");
        retMap.put("sign", sign);
        return retMap;
    }

    private String getUpLoadFileName(String filePath) {
        if (filePath == null) return "";
        if (filePath.indexOf("/") != -1) {
            return filePath.substring(filePath.lastIndexOf("/") + 1);
        } else if (filePath.indexOf("\\") != -1) {
            return filePath.substring(filePath.lastIndexOf("\\") + 1);
        }
        return filePath;

    }

    private String trimFileType(String filePath) {
        return filePath.substring(0, filePath.indexOf("."));

    }

}
